﻿using AutoMapper;
using B.S.Database.Domain.Entity;
using B.S.Database.ErrorCode;
using B.S.Database.Interface.Interface;
using B.S.Database.Write.Api.Application.Commands.Processing;
using MediatR;
using NuGet.Protocol.Plugins;

namespace B.S.Database.Write.Api.Application.CommandHandler.Processing
{
    public class SupplierCreateCommandHandler : IRequestHandler<SupplierCreateCommands, Apiresult<object>>
    {
        private readonly IBaseResotity<Supplier> supplierRepo;
        private readonly IMapper mapper;

        public SupplierCreateCommandHandler(IBaseResotity<Supplier> SupplierRepo,IMapper mapper)
        {
            supplierRepo = SupplierRepo;
            this.mapper = mapper;
        }
        public Task<Apiresult<object>> Handle(SupplierCreateCommands request, CancellationToken cancellationToken)
        {
            Apiresult<object> res = new Apiresult<object>();
            using (var tran = supplierRepo.Db.Database.BeginTransaction())
            {
                try
                {
                    // 唯一性校验：如果存在则修改，否则添加
                    var exists = supplierRepo.GetAll().FirstOrDefault(x => x.TraceabilityId == request.TraceabilityId);
                    if (exists != null)
                    {
                        // 直接更新 exists 的属性
                        // 请将下方字段替换为你的实际字段
                        exists.Batch_Number = request.Batch_Number;
                        // 例如：
                        // exists.SomeField = request.SomeField;
                        // exists.AnotherField = request.AnotherField;
                        supplierRepo.Update(exists);
                        res.Code = ApiEnums.成功;
                        res.Message = "已存在，执行修改操作";
                    }
                    else
                    {
                        // 添加
                        var list = mapper.Map<Supplier>(request);
                        supplierRepo.Add(list);
                        res.Code = ApiEnums.成功;
                        res.Message = "添加成功";
                    }
                    tran.Commit();
                }
                catch (Exception)
                {
                    res.Code = ApiEnums.错误;
                    res.Message = ApiEnums.错误.ToString();
                    tran.Rollback();
                    throw;
                }
            }
            return Task.FromResult(res);
        }
    }
}
